package com.zcl.IO.fileStream;

import org.junit.Test;

import java.io.*;

/**
 * @Description:
 * @author: zcl
 * @date: 2022/3/15  11:17
 *
 * 测试FileInputStream FileOutputStream使用
 */
public class FileInputOutputStreamTest {

    /**
     *
     */
    @Test
    public void testFileInputStream() {
        FileInputStream fileInputStream = null;
        try {
            //1.创建File对象
            File file = new File("src\\com\\zcl\\IO\\fileStream\\input.txt");
            //2.创建输入流对象
            fileInputStream = new FileInputStream(file);
            //3.读数据
            int len;
            byte[] buffer = new byte[1024];
            while ((len = fileInputStream.read(buffer)) != -1){
                String string = new String(buffer,0,len);
                System.out.println(string);
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            //4.关闭流
            try {
                if (fileInputStream !=null) {
                    fileInputStream.close();
                }
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    /**
     * 实现对图片的赋值
     */
    @Test
    public void testFileInputOutputStream() throws FileNotFoundException {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            File input = new File("src\\com\\zcl\\IO\\fileStream\\p1.jpg");
            File output = new File("src\\com\\zcl\\IO\\fileStream\\p2.png");

            fileInputStream = new FileInputStream(input);
            fileOutputStream = new FileOutputStream(output);

            byte[] buffer = new byte[1024];
            int len;
            while((len = fileInputStream.read(buffer)) != -1){
                fileOutputStream.write(buffer,0,len);
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }

    }

}
